//
//  ValuePickerCellData.m
//  18Birdies
//
//  Created by Eric Cheng on 2018/7/5.
//  Copyright © 2018年 Lc. All rights reserved.
//

#import "ValuePickerCellData.h"
#import "LcFoundation.h"
#import "NumberPickerCell.h"

@implementation ValuePickerCellData

+ (ValuePickerCellData*)cellDataWithValues:(NSArray<NSString*>*)values
                           onPickedHandler:(ValueChangeHandler)onPickedHandler {
  LC_CHECK_NOT_EMPTY(values);
  ValuePickerCellData* cellData = [[self alloc] init];
  cellData.values = values;
  cellData.onPickedHandler = onPickedHandler;
  cellData.clickable = NO;

  cellData.cellHeight = 162;
  return cellData;
}

- (Class)cellClazz {
  return NumberPickerCell.class;
}

- (NSString*)nibName {
  return @"NumberPickerCell";
}

- (void)refreshCell:(NumberPickerCell*)cell {
  [super refreshCell:cell];
  if (self.hidden) {
    return;
  }
  cell.pickerView.dataSource = self;
  cell.pickerView.delegate = self;
  [cell.pickerView selectRow:[self indexOfCurrentValue] inComponent:0 animated:NO];
  [cell.pickerView reloadAllComponents];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView {
  return 1;
}

- (NSInteger)pickerView:(UIPickerView*)pickerView numberOfRowsInComponent:(NSInteger)component {
  return self.values.count;
}

- (NSString*)pickerView:(UIPickerView*)pickerView
            titleForRow:(NSInteger)row
           forComponent:(NSInteger)component {
  return self.values[row];
}

- (void)pickerView:(UIPickerView*)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component {
  self.value = self.values[row];
  if (self.onPickedHandler != nil) {
    self.onPickedHandler(self);
  }
}

- (int)indexOfCurrentValue {
  for (int i = 0; i < self.values.count; ++i) {
    if ([self.value isEqualToString:self.values[i]]) {
      return i;
    }
  }
  LC_FAIL();
  return 0;
}

@end
